<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Log;

class Article extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {

        $cat_id = $this->request->param('id');
        if(null==$cat_id){
            $this->error('非法操作');
        }
        if((null!=$this->request->param('id'))&&(null!=$this->request->param('articleid'))){
            $article_id = $this->request->param('articleid');
            $article = Db('article')->where(['id'=>$article_id])->find();
        }else if(null!=$this->request->param('id')){
            $article = Db('article')->where(['category_id'=>$cat_id])->order('id','asc')->find();
        }else{
            $this->error('非法操作');
        }

        $category = Db('category')->where(['id'=>$cat_id])->find();
        $activetype_id = $category['activetype_id'];
        $banner = Db('activetype')->where(['id'=>$activetype_id])->find();
        $this->assign('banner',$banner);
        $this->assign('activetype',$banner);

        $this->assign('article',$article);

        $this->assign('cate',$activetype_id);

        if(null==$category){
            $category['image'] = $banner['image'];
        }
        $this->assign('category',$category);







        /*


        if($article){

            $article_id = $article['id'];  //4

            //下一篇文章
            //判断比4大的文章有没
            $xarticle = Db('article')->where('id','>',$article_id)->order('id', 'asc')->limit(1)->select();
            if($xarticle){
                $this->assign('isnext',1);
                $this->assign('xarticle',$xarticle);
            }else{
                $this->assign('isnext',0);
            }
            //上一篇文章

            if($article){
                $sarticle = Db('article')->where('id','<',$article_id)->order('id', 'desc')->limit(1)->select();
                if($sarticle){
                    $this->assign('isprev',1);
                    $this->assign('sarticle',$sarticle);
                }else{
                    $this->assign('isprev',0);
                }
            }

        }

        */


        if($article) {

            $article_id = $article['id'];  //4

            //下一篇文章
            //判断比4大的文章有没
            $xarticle = Db('article')->where('category_id',$cat_id)->where('id', '>', $article_id)->order('id', 'asc')->limit(1)->select();
            $sarticle = Db('article')->where('category_id',$cat_id)->where('id', '<', $article_id)->order('id', 'desc')->limit(1)->select();

            if ((null != $xarticle) && (null != $sarticle)) {

                //上一篇，下一篇都有
                $this->assign('flag', 8);
                $this->assign('xarticle',$xarticle);
                $this->assign('sarticle',$sarticle);
            } else if (null != $xarticle) {
                //下一篇有
                $this->assign('flag', 2);
                $this->assign('xarticle',$xarticle);
            } else if (null != $sarticle) {

                //上一篇有
                $this->assign('flag', 1);
                $this->assign('sarticle',$sarticle);
            } else {

                //都没有
                $this->assign('flag', 0);
            }
        }


        $jsapiTicket = $this->getJsApiTicket();
        //不对url进行过滤
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signpackage = array(
            "appId"     => config('site.appid'),
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        $this->assign('signpackage',$signpackage);

        //分享

        $myshare = Db('myshare')->where(['activetype_id'=>$activetype_id])->find();
        if(null==$myshare){
            $myshare['name'] = config('site.name');
            $myshare['link'] = $this->request->domain();
            $myshare['description'] = config('site.name');
            $myshare['image'] = config('site.codeimg');
        }else{
            $myshare['image'] = $this->request->domain().$myshare['image'];
        }



        $this->assign('myshare',$myshare);

        return $this->view->fetch();
    }

    public function isshare()
    {


        /*
        $addtime = date('Y-m-d H:i:s',1585925360);
        $addtime = strtotime($addtime);
        echo $addtime;
        echo '<br/>';
        $today = date('Y-m-d',time()).'23:59:59';
        $today = strtotime($today);
        echo $today;

        die;
        */


        $openid = $this->request->post('openid');
        $activetype_id = $this->request->post('activetype_id');
        $share_type = $this->request->post('share_type');
        $wxshare = Db('wxshare')
            ->where(['activetype_id'=>$activetype_id,'openid'=>$openid,'share_type'=>$share_type])
            ->order('id','desc')
            ->find();


        if($wxshare!=null){
            $addtime = strtotime(date('Y-m-d',$wxshare['addtime']));
            $today = strtotime(date('Y-m-d'));
            if($addtime<$today) {
                //允许
                $info['code'] = 1;
                $info['mess'] = 'ok';
                echo json_encode($info);
                die;
            }else{
                $info['code'] = 0;
                $info['mess'] = 'fail';
                echo json_encode($info);
                die;
            }
        }else{
            $info['code'] = 1;
            $info['mess'] = 'ok';
            echo json_encode($info);
            die;
        }


    }

    public function mark()
    {

        $openid = $this->request->post('openid');
        $token = $this->request->post('token');
        $url = $this->request->post('url');
        $cate = $this->request->post('cate');
        $addtime = time();
        $share_type = $this->request->post('share_type');

        $wxshare = Db('wxshare')
            ->where(['activetype_id'=>$cate,'openid'=>$openid,'share_type'=>$share_type])
            ->order('id','desc')
            ->find();
        if($wxshare!=null){
            $addtime = strtotime(date('Y-m-d',$wxshare['addtime']));
            $today = strtotime(date('Y-m-d'));
            if($addtime<$today) {
                //允许
                Db('wxshare')
                    ->where(['activetype_id'=>$cate,'openid'=>$openid,'share_type'=>$share_type])
                    ->update(['addtime'=>time(),'url'=>$url,'token'=>$token]);
                if($share_type==1){
                    Db('activetype')->where(['id'=>$cate])->setInc('fxnum',1);
                }else if($share_type==2){
                    Db('activetype')->where(['id'=>$cate])->setInc('xznum',1);
                }else{
                    
                }

                $info['code'] = 1;
                $info['mess'] = 'ok';
                echo json_encode($info);
                die;
            }else{
                $info['code'] = 0;
                $info['mess'] = 'fail';
                echo json_encode($info);
                die;
            }
        }else{
            //第一次
            $res = Db('wxshare')->insert(['openid'=>$openid,'token'=>$token,'activetype_id'=>$cate,'url'=>$url,'addtime'=>$addtime,'share_type'=>$share_type]);
            if($share_type==1){
                Db('activetype')->where(['id'=>$cate])->setInc('fxnum',1);
            }else if($share_type==2){
                Db('activetype')->where(['id'=>$cate])->setInc('xznum',1);
            }else{

            }
            $info['code'] = 1;
            $info['mess'] = 'ok';
            echo json_encode($info);
            die;
        }
        /*
        if($wxshare!=null){
            $addtime = strtotime(date('Y-m-d H:i:s',$wxshare['addtime']));
            $today = strtotime(date('Y-m-d',time()).'23:59:59');
            if($today>=$addtime) {
                Db('wxshare')
                    ->where(['activetype_id'=>$cate,'openid'=>$openid])
                    ->update(['addtime'=>time(),'url'=>$url,'token'=>$token]);
                Db('activetype')->where(['id'=>$cate])->setInc('fxnum',1);
                $info['code'] = 1;
                $info['mess'] = 'ok';
            }else{
                $info['code'] = 0;
                $info['mess'] = 'fail';
            }
        }else{
            //第一次
            $res = Db('wxshare')->insert(['openid'=>$openid,'token'=>$token,'activetype_id'=>$cate,'url'=>$url,'addtime'=>$addtime]);
            Db('activetype')->where(['id'=>$cate])->setInc('fxnum',1);
            $info['code'] = 1;
            $info['mess'] = 'ok';

        }
        */

        //echo json_encode($info);


    }



    //获取jsapiTicket
    private function getJsApiTicket() {
        $data = Db('weixin_token')
            ->where('type','jsapi_ticket')
            ->find();
        if($data['expire_time'] < time()){
            //       //如果数据库内令牌已失效 令牌有效期
            $accessToken = $this->getAccessToken();
            // print_r($accessToken);
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = $this->http_curl($url);
            $res = json_decode($res);


            if(!empty($res->errcode)){
                $res->remarks = 'api_ticket获取失败';
                die(json_encode($res));
            }


            if ($res->ticket) {
                Db('weixin_token')
                    ->where('type','jsapi_ticket')
                    ->update([
                        'expire_time'=> time()+7000,
                        'code'=>$res->ticket
                    ]);
            }
            return $res->ticket;
        }
        return $data['code'];
    }
    //获取AccessToken
    private function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = Db('weixin_token')
            ->where('type','access_token')
            ->find();
        // print_r($data);
        $appid = config('site.appid');
        $appsecret = config('site.appsecret');
        if($data['expire_time']<time()){
            //如果数据库内Token过期
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
            $res = json_decode($this->http_curl($url));
            //如果接口错误
            if(!empty($res->errcode)){
                $res->remarks = 'accessToken获取失败';
                die(json_encode($res));
            }
            $access_token = $res->access_token;
            //更新数据库内token
            if ($access_token) {
                Db('weixin_token')
                    ->where('type','access_token')
                    ->update([
                        'expire_time'=> time()+7000,
                        'code'=>$access_token
                    ]);
            }
            return $res->access_token;
        }
        return $data['code'];
    }





    //创建随机字符
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    //http获取
    public function  http_curl($url,$data=null){
        //1.初始化，创建一个新cURL资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_HEADER, 0);
        if(!empty($data)){
            curl_setopt($ch,CURLOPT_POST,1);

            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//禁止curl资源直接输出
        //3.抓取URL并把它传递给浏览器
        $res=curl_exec($ch);
        //4.关闭cURL资源，并且释放系统资源
        curl_close($ch);
        return $res;
    }




}
